#!/usr/bin/python

import sys
import Image

def medium_filter(inf):
	im = Image.open(inf)
        (width, height) = im.size
	nim = im.copy()
	
	pix = nim.load()
	for x in range(width):
		for y in range(height):
			list = []
			
			list.append(pix[x,y])
			if y > 0:
				list.append(pix[x,y-1])

			if y < height -1:
				list.append(pix[x,y+1])
			
			if x > 0:	
				list.append(pix[x-1,y])
				if y > 0:
					list.append(pix[x-1,y-1])
				if y < height - 1:
					list.append(pix[x-1,y+1])
		
			if x < width -1 :
				list.append(pix[x+1,y])
				if y > 0:
					list.append(pix[x+1,y-1])
				if y < height -1:
					list.append(pix[x+1,y+1])
			
			count = len(list)
			for idx in range(9 - count):
				list.append(255)
			
			list.sort()
			pix[x, y] = list[4]
	
	nim.save('/tmp/result.pgm')
	
	
	
if __name__ == '__main__':
        argvs = sys.argv
        argc  = len(argvs)
        if ( argc != 2 ):
                print "Usage: tool <FileName>"
                sys.exit(1)
        medium_filter(argvs[1])




	
